﻿using AuthCenter.API.Application.Command.Menu;
using AuthCenter.Domain.Menu;
using AuthCenter.ErrorCode;
using AuthCenter.Intertructrue.Interface;
using AutoMapper;
using MediatR;
using Yitter.IdGenerator;

namespace AuthCenter.API.Application.Handler.Menu
{
    public class CreateMenuHandler : IRequestHandler<CreateMenuCommand, APIResult<int>>
    {
        private readonly IBaseRepository<MenuModel> menuRepo;
        private readonly IMapper mapper;

        public CreateMenuHandler(IBaseRepository<MenuModel> menuRepo,
                                 IMapper mapper)
        {
            this.menuRepo = menuRepo;
            this.mapper = mapper;
        }
        public Task<APIResult<int>> Handle(CreateMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var res = menuRepo.GetAll().FirstOrDefault(x => x.ParentId == request.ParentId && x.MenuName == request.MenuName);
            if (res != null)
            {
                result.Message = "此菜单下菜单名称已存在";
                result.Code = APIEnum.Fail;
                return Task.FromResult(result);
            }
            var model = mapper.Map<MenuModel>(request);
            model.Id = YitIdHelper.NextId();
            model.CreateName = request.LoginName;
            model.CreateDate = DateTime.Now;
            int r = menuRepo.AddAsync(model).Result;
            if (r > 0)
            {
                result.Message = "菜单添加成功";
                result.Code = APIEnum.Ok;
                result.Data = r;
            }
            else
            {
                result.Message = "菜单添加失败";
                result.Code = APIEnum.Fail;
                result.Data = r;
            }
            return Task.FromResult(result);
        }
    }
}
